package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.dto.UserThreadLocalUtil;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author Wq
 * @since 2022-10-09
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {

    @Override
    public ResponseResult pageByCondition(WmNewsPageDto dto) {
        //1、参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        LambdaQueryWrapper<WmNews> wrappers = new LambdaQueryWrapper<>();
        //状态
        Integer status = dto.getStatus();
        if (status != null) {
            wrappers.eq(WmNews::getStatus, status);
        }
        //关键字
        String keyword = dto.getKeyword();
        wrappers.like(StringUtils.isNotBlank(keyword), WmNews::getTitle, keyword);

        //频道id
        Integer channelId = dto.getChannelId();
        if (channelId != null) {
            wrappers.eq(WmNews::getChannelId, channelId);
        }
        //发布日期
        Date beginPubDate = dto.getBeginPubDate();
        Date endPubDate = dto.getEndPubDate();
        if (ObjectUtils.isNotEmpty(beginPubDate) && ObjectUtils.isNotEmpty(endPubDate)) {
            wrappers.between(WmNews::getPublishTime, beginPubDate, endPubDate);
        }
        //隐藏条件  当前登录用户id
        User user = UserThreadLocalUtil.get();
        if (user != null) {
            wrappers.eq(WmNews::getUserId, user.getUserId());
        }
        //按照发布时间排序
        wrappers.orderByDesc(WmNews::getCreatedTime);
        Page<WmNews> page = this.page(new Page<>(dto.getPage(), dto.getSize()), wrappers);
        return new PageResponseResult(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }

    @Autowired
    @Lazy  //解决循环依赖引用的问题
    private IAuditService auditService;

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //通过id判断是新增还是修改操作
        if (dto.getId() != null) {
            //修改操作   需要删除中间表的数据
            deleteRelation(dto.getId());
        }
        //新增和修改文章
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);

        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());

        //从请求参数中获取图片
        List<ImageDto> images = dto.getImages();
        wmNews.setImages(JSON.toJSONString(images));

        //从文章获取图片
        List<ImageDto> imageListFromContent = getImagesFromContent(dto.getContent());
        //类型为-1 封面图片从内容中获取
        if (dto.getType() == -1) {
            //type 文章布局 0 无图文章  1 单图文章 3 多图文章
            int size = imageListFromContent.size();
            if (size == 0) {
                //无图
                wmNews.setType(0);
            } else if (size > 0 && size < 3) {
                //截取一张作为封面
                wmNews.setType(1);
                imageListFromContent = imageListFromContent.subList(0, 1);
            } else {
                //三张图作为封面
                wmNews.setType(3);
                imageListFromContent = imageListFromContent.subList(0, 3);
            }
            wmNews.setImages(JSON.toJSONString(imageListFromContent));
        }
        this.saveOrUpdate(wmNews);

        if (dto.getStatus() != 0) {
            //保存文章的图片
            saveRelation(imageListFromContent, wmNews.getId(), 0);//引用类型  0 内容引用 1 主图引用
            //保存封面的图片
            saveRelation(images, wmNews.getId(), 1);

            //自媒体文章审核
            auditService.audit(wmNews); // 阿里云做文本 图片审核 比较耗时  异步
        }
        return ResponseResult.okResult();
    }


    private void saveRelation(List<ImageDto> imageDtos, Integer newsId, Integer type) {
        int ord = 0;
        for (ImageDto imageDto : imageDtos) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(imageDto.getId());
            wmNewsMaterial.setNewsId(newsId);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd(ord);
            wmNewsMaterialService.save(wmNewsMaterial);
            ord++;
        }

    }

    private List<ImageDto> getImagesFromContent(String content) {
        List<ImageDto> imageDtoList = new ArrayList<>();
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if ("image".equals(contentDto.getType())) {
                ImageDto imageDto = new ImageDto();
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtoList.add(imageDto);
            }
        }
        return imageDtoList;
    }


    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;

    private void deleteRelation(Integer newsId) {
        //根据newsId删除相关信息
        //delete from wm_news_material where news_id = ?
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getNewsId, newsId);
        wmNewsMaterialService.remove(wrapper);
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;


    @Value("${topic.upDownTopic}")
    private String upDownTopic;

    /**
     * 文章上下架
     *
     * @param dto dto
     * @return {@code ResponseResult}
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //判断当前是否有登录人
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Integer id = dto.getId();
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer enable = dto.getEnable();
        wmNews.setEnable(enable == 1);
        //根据id修改自媒体文章状态
        this.updateById(wmNews);

        //远程调用  修改文章微服务状态
        //使用kafka异步修改
        Long articleId = wmNews.getArticleId();
        Map map = new HashMap();
        map.put("articleId", articleId);
        //is_down  1 true 下架    0  false 上架
        map.put("enable", enable == 0);
        kafkaTemplate.send(upDownTopic, JSON.toJSONString(map));
        return ResponseResult.okResult();
    }
}
